﻿using System.Collections.ObjectModel;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using MoneyBook.ComponentModel;
using MoneyBook.Web.Models;
using MoneyBook.Web.Services;
using MoneyBook.Reflection;
using System.Windows.Data;
using System.Windows.Markup;

namespace MoneyBook.Views {

    public partial class MainViewModel : ViewModelBase {

        [ExcludeValidation]
        [ViewModelProperty]
        private ObservableCollection<Account> accounts_;
        
        [ExcludeValidation]
        [ViewModelProperty]
        private ObservableCollection<Item> items_;

        public void LoadAccounts() {
            AccountContext context = new AccountContext();
            EntityQuery<Account> query = context.GetAccountsByMemberQuery(WebContext.Current.User.MemberID);

            context.Load(query, (op) => {
                if (op.HasError) {
                    //TODO : エラー処理
                    op.MarkErrorAsHandled();
                } else {
                    ObservableCollection<Account> accounts = new ObservableCollection<Account>(op.Entities);
                    Account mainAccount = accounts.FirstOrDefault(a => a.AccountId == WebContext.Current.User.MainAccountId);
                    if(mainAccount != null){
                        mainAccount.IsMain = true;
                    }
                    this.Accounts = accounts;
                }
            },null);
        }

        public void AddedNewAccount(Account addedAccount) {
            this.Accounts.Add(addedAccount);
        }

        public void AddedNewItem(Item addedItem) {
            if (this.Items == null) {
                return;
            }
            this.Items.Add(addedItem);
        }

        public void LoadAccountItems(Account account) {
            ItemContext context = new ItemContext();
            context.Load(context.GetItemsByAccountQuery(account.AccountId), op => {
                if (op.HasError) {
                    //TODO : エラー処理
                    op.MarkErrorAsHandled();
                } else {
                    ObservableCollection<Item> items = new ObservableCollection<Item>(op.Entities);
                    this.Items = items;
                }
            }, null);
        }

        protected override EnhancePropertyAttributeType GetEnhancePtopertyAttributeType() {
            return null;

        }
    }
}
